package com.example.li_han.servlet;


import com.example.li_han.service.AdminService;
import com.google.gson.Gson;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

//修改管理员用户密码
@WebServlet(name = "AdminUpdatePwd", value = "/AdminUpdatePwd")
public class AdminUpdatePwd extends HttpServlet {
    private Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf-8");

        BufferedReader br = req.getReader();
        StringBuilder sbuffer = new StringBuilder();
        String s;

        Map<String, Object> resultMap = new HashMap<>();

        try {
            while((s = br.readLine()) != null) {
                sbuffer.append(s);
            }

            String requestBody = sbuffer.toString();
            System.out.println("管理员修改密码请求: " + requestBody);

            // 解析JSON数据
            Map<String, Object> requestData = gson.fromJson(requestBody, Map.class);

            int adminId = ((Number) requestData.get("adminId")).intValue();
            String oldPassword = (String) requestData.get("oldPassword");
            String newPassword = (String) requestData.get("newPassword");

            if (oldPassword == null || oldPassword.trim().isEmpty() ||
                    newPassword == null || newPassword.trim().isEmpty()) {
                resultMap.put("code", 500);
                resultMap.put("msg", "原密码和新密码不能为空");
                sendResponse(resp, resultMap);
                return;
            }

            // 验证原密码
            AdminService adminService = new AdminService();
            if (!adminService.validatePassword(adminId, oldPassword)) {
                resultMap.put("code", 500);
                resultMap.put("msg", "原密码错误");
                sendResponse(resp, resultMap);
                return;
            }

            // 更新密码
            int result = adminService.updatePassword(adminId, newPassword);

            if (result > 0) {
                resultMap.put("code", 200);
                resultMap.put("msg", "密码修改成功");
            } else {
                resultMap.put("code", 500);
                resultMap.put("msg", "密码修改失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", 500);
            resultMap.put("msg", "服务器异常: " + e.getMessage());
        }

        sendResponse(resp, resultMap);
    }

    private void sendResponse(HttpServletResponse resp, Map<String, Object> resultMap) throws IOException {
        String json = gson.toJson(resultMap);
        resp.getWriter().write(json);
    }
}